package cn.wit.summit.chwan.ui.service;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import java.lang.reflect.Method;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.VersionDto;
import cn.wit.summit.chwan.net.okhttplib.HttpInfo;
import cn.wit.summit.chwan.net.okhttplib.OkHttpUtil;
import cn.wit.summit.chwan.net.okhttplib.callback.ProgressCallback;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.ui.receiver.BroadcastAction;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.PermissionManagerUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Alan on 2018/5/16.
 */

public class AppUpdataVersionService extends Service {

    private final int REQUEST_CODE_BROADCAST = 0X0001;//发送广播的请求码
    private final String BROADCAST_ACTION_CLICK = "servicetask";//发送广播的action
    private Notification notification;//通知
    private final int NOTIFICATION_ID = 1;//通知的Id
    private NotificationManager notificationManager;//通知管理器
    private RemoteViews mRemoteViews;//通知栏的远程View
    //自定义保存路径，Environment.getExternalStorageDirectory()：SD卡的根目录
    private String filePath;
    private MyBroadcastReceiver myBroadcastReceiver;

    private String fileName;
    private String appName;
    private String fileURL;
    private final String requestTag = "download-tag-1001";//请求标识

    private String channelId = "channelId";
    private VersionDto versionDto;

    private boolean isDownloadSuccess = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        appName = getResources().getString(R.string.app_name);
        if (intent!=null) {
            versionDto = (VersionDto) intent.getSerializableExtra("data");
            fileURL = versionDto.getAndroidUrl();
            registerBroadCast();
            download();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 注册按钮点击广播*
     */
    private void registerBroadCast() {
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_ACTION_CLICK);
        registerReceiver(myBroadcastReceiver, filter);
    }

    /**
     * 更新通知界面的按钮的广播
     */
    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BROADCAST_ACTION_CLICK) && isDownloadSuccess) {
                toInstalApk(context);
            }
        }
    }

    private void toInstalApk(Context context) {
        collapseStatusBar(context);
        if (checkIntallPermission(context)) {
            notificationManager.cancel(NOTIFICATION_ID);
            APKUtils.getInstance(AppUpdataVersionService.this).installAPK(
                    AppUpdataVersionService.this,
                    filePath+fileName,
                    "-1");
        } else {
            Intent intent = new Intent(BroadcastAction.ACTION_INSTALL_APK);
            intent.putExtra("permisson", PermissionManagerUtil.PERM_INSTALL);
            sendBroadcast(intent);
        }
    }

    private boolean checkIntallPermission(Context mContext) {
        boolean haveInstallPermission = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            haveInstallPermission = true;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (EasyPermissions.hasPermissions(mContext, Manifest.permission.REQUEST_INSTALL_PACKAGES)) {
                haveInstallPermission = true;
            }
        } else {
            haveInstallPermission = true;
        }
        return haveInstallPermission;
    }

    /**
     *
     * 收起通知栏
     * @param context
     */
    public static void collapseStatusBar(Context context) {
        try {
            @SuppressLint("WrongConstant")
            Object statusBarManager = context.getSystemService("statusbar");
            Method collapse;
            if (Build.VERSION.SDK_INT <= 16) {
                collapse = statusBarManager.getClass().getMethod("collapse");
            } else {
                collapse = statusBarManager.getClass().getMethod("collapsePanels");
            }
            collapse.invoke(statusBarManager);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

        /**
         * 下载文件
         */
    private void download() {
        filePath = MyApplication.getMyApplication().getAppRootPath();
        fileName = fileURL.substring(fileURL.lastIndexOf("/")+1);
        final HttpInfo info = HttpInfo.Builder()
                .addDownloadFile(fileURL, fileName, new ProgressCallback() {
                    @Override
                    public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
                        updateNotification(percent);
                        LogUtils.e("下载进度：" + percent);
                    }

                    @Override
                    public void onResponseMain(String filePath, HttpInfo info) {
                        LogUtils.e("下载结果：" + info.getRetDetail());
                        if (StringUtils.isEmpty(info.getRetDetail())) {
                            isDownloadSuccess = false;
                            downloadFail();
                        } else {
                            isDownloadSuccess = true;
                            downloadSuccess();
                        }
                    }
                })
                .build();
        OkHttpUtil.Builder().setReadTimeout(30).setDownloadFileDir(filePath)
                .build(requestTag)//绑定请求标识
                .doDownloadFileAsync(info);

        showNotificationProgress(this);
    }

    /**
     * 显示一个下载带进度条的通知
     *
     * @param context 上下文
     */
    public void showNotificationProgress(Context context) {
        /**进度条通知构建**/
        NotificationCompat.Builder builderProgress = new NotificationCompat.Builder(context, channelId);
        /**设置为一个正在进行的通知**/
        builderProgress.setOngoing(true);
        /**设置小图标**/
        builderProgress.setSmallIcon(R.mipmap.ic_launcher);

        /**新建通知自定义布局**/
        mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_app_updata_view);
        /**进度条ProgressBar**/
        mRemoteViews.setProgressBar(R.id.pb, 100, 0, false);
        /**提示信息的TextView**/
//        mRemoteViews.setTextViewText(R.id.tv_name, fileName);
        mRemoteViews.setTextViewText(R.id.tv_name, appName+"更新中...");
        /**设置左侧小图标*/
        mRemoteViews.setImageViewResource(R.id.iv, R.mipmap.ic_launcher);
        mRemoteViews.setTextViewText(R.id.tv_status, getStringDate());
        /**设置通过广播形式的PendingIntent**/
        Intent intent = new Intent(BROADCAST_ACTION_CLICK);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE_BROADCAST, intent, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.notifyRootLl, pendingIntent);
        /**设置自定义布局**/
        builderProgress.setContent(mRemoteViews);
        /**设置滚动提示**/
        builderProgress.setTicker("开始下载...");
        builderProgress.setDefaults(NotificationCompat.DEFAULT_LIGHTS);
        builderProgress.setVibrate(new long[]{0});
        builderProgress.setSound(null);
        notification = builderProgress.build();
        /**设置不可手动清除**/
        notification.flags = Notification.FLAG_NO_CLEAR;
        /**获取通知管理器**/
        notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            createNotificationChannel();
        }
        /**发送一个通知**/
        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        NotificationChannel channel = new NotificationChannel(channelId
                , "channelName", NotificationManager.IMPORTANCE_LOW);
//        channel.setShowBadge(true);
        channel.setDescription("no sound");
        channel.setSound(null,null);
        channel.enableLights(false);
        channel.enableVibration(false);
        notificationManager.createNotificationChannel(channel);
    }

    /**
     * 下载更改进度
     *
     * @param current 下载进度
     */
    private void updateNotification(int current) {
        mRemoteViews.setProgressBar(R.id.pb, 100, current, false);
        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    /**
     * 下载成功
     */
    private void downloadSuccess() {
        mRemoteViews.setTextViewText(R.id.tv_name, appName+"下载完成,点击安装");
        notificationManager.notify(NOTIFICATION_ID, notification);

        toInstalApk(AppUpdataVersionService.this);
    }

    /**
     * 下载失败
     */
    private void downloadFail() {
        mRemoteViews.setTextViewText(R.id.tv_name, appName+"下载失败");
        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    /**
     * 格式化文件大小
     *
     * @param size
     * @return
     */
    private String formatSize(long size) {
        String format;
        if (size >= 1024 * 1024) {
            format = byteToMB(size) + "M";
        } else if (size >= 1024) {
            format = byteToKB(size) + "k";
        } else {
            format = size + "b";
        }
        return format;
    }

    /**
     * byte转换为MB
     *
     * @param bt 大小
     * @return MB
     */
    private float byteToMB(long bt) {
        int mb = 1024 * 1024;
        float f = (float) bt / (float) mb;
        float temp = (float) Math.round(f * 100.0F);
        return temp / 100.0F;
    }

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * byte转换为KB
     *
     * @param bt 大小
     * @return K
     */
    private int byteToKB(long bt) {
        return Math.round((bt / 1024));
    }

    /**
     * 销毁时取消下载，并取消注册广播，防止内存溢出
     */
    @Override
    public void onDestroy() {
        notificationManager.cancel(NOTIFICATION_ID);
        OkHttpUtil.getDefault().cancelRequest(requestTag);
        if (myBroadcastReceiver != null) {
            unregisterReceiver(myBroadcastReceiver);
        }
        super.onDestroy();
    }
}
